package work.chenxr.restful.encrypt.advice;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.ObjectUtils;
import org.dromara.hutool.crypto.KeyUtil;
import org.dromara.hutool.crypto.asymmetric.KeyType;
import org.dromara.hutool.crypto.asymmetric.RSA;
import org.dromara.hutool.crypto.symmetric.AES;
import org.dromara.hutool.crypto.symmetric.SymmetricAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import work.chenxr.restful.encrypt.annotation.ApiSecurity;

import javax.crypto.SecretKey;
import java.lang.reflect.Method;

/**
 * @Author Chenxr
 * @Date 2023/10/28
 * @Description 加密返回参数
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Value("${cipher-security.enable}")
    private boolean enableCipherSecurity;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (!enableCipherSecurity) {
            return false;
        }

        // 检测注解是否开启加密
        Method method = returnType.getMethod();
        if (!ObjectUtils.isEmpty(method)) {
            ApiSecurity apiSecurity = method.getDeclaredAnnotation(ApiSecurity.class);
            if (!ObjectUtils.isEmpty(apiSecurity)) {
                return apiSecurity.encrypt();
            }
        }

        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        //TODO 密钥可以配置在yml中，也可通过安全框架获取，例如：SecurityUser.getRsaPrivateKey()
        String rsaPrivateKey = "";
        RSA rsa = new RSA(rsaPrivateKey, null);

        // 生成AES密钥
        SecretKey aesSecretKey = KeyUtil.generateKey(SymmetricAlgorithm.AES.getValue());
        // 将AES密钥通过RSA私钥加密后的密文设置到请求头中
        response.getHeaders().set("secret-key", rsa.encryptBase64(aesSecretKey.getEncoded(), KeyType.PrivateKey));

        // 加密返回参数
        AES aes = new AES(aesSecretKey.getEncoded());
        String content = JSON.toJSONString(body);
        return aes.encryptBase64(content);
    }
}
